cmake_minimum_required(VERSION 3.15)

# 在 project() 之前手动包含工具链文件
# 检查 CMAKE_TOOLCHAIN_FILE 是否已定义且非空
if(DEFINED CMAKE_TOOLCHAIN_FILE AND CMAKE_TOOLCHAIN_FILE)
    message(STATUS "Using toolchain file: ${CMAKE_TOOLCHAIN_FILE}")
    if(EXISTS "${CMAKE_TOOLCHAIN_FILE}")
        include(${CMAKE_TOOLCHAIN_FILE})
        message(STATUS "Toolchain ${CMAKE_TOOLCHAIN_FILE} file included successfully")
    else()
        message(FATAL_ERROR "Toolchain file not found: ${CMAKE_TOOLCHAIN_FILE}")
    endif()
else()
    message(WARNING "CMAKE_TOOLCHAIN_FILE is not set or empty")
    # 可以在这里包含默认的工具链文件
    if(EXISTS "${CMAKE_SOURCE_DIR}/cmake/x86-toolchain.cmake")
        include(${CMAKE_SOURCE_DIR}/cmake/x86-toolchain.cmake)
        message(STATUS "Using default toolchain file")
    endif()
endif()


project(elf-load-test
        VERSION 1.0.0
        LANGUAGES C
        )  

set(TARGET_FILE "main.elf")

include_directories(${TARGET_FILE} inc)
aux_source_directory(src PROJECT_CSRC)
add_executable(${TARGET_FILE} ${PROJECT_CSRC})

target_link_directories(${TARGET_FILE} PUBLIC .)
set(LINKER_SCRIPT "link.ld")
get_filename_component(LINKER_SCRIPT_ABS "${LINKER_SCRIPT}" ABSOLUTE)


# 添加其他必要的链接选项
target_link_options(${TARGET_FILE} PUBLIC
    "-T${LINKER_SCRIPT_ABS}"
    "-Wl,-Map=${TARGET_FILE}.map" 
    "-specs=nosys.specs"
    "-Wl,--gc-sections"
    "-nostartfiles"
    "-nostdlib"
    "-std=c99"
)

# 设置编译选项
target_compile_options(${TARGET_FILE} PUBLIC
    -mcpu=cortex-m3
    -mthumb
    -ffunction-sections
    -fdata-sections
    -Og
    -g
)

# 添加 ELF 到 BIN 的转换（在构建 main 后自动执行）
add_custom_command(TARGET ${TARGET_FILE} POST_BUILD
    COMMAND ${CMAKE_OBJCOPY} -O binary $<TARGET_FILE:${TARGET_FILE}> $<TARGET_FILE:${TARGET_FILE}>.bin
    COMMAND ${CMAKE_OBJCOPY} -O ihex $<TARGET_FILE:${TARGET_FILE}> $<TARGET_FILE:${TARGET_FILE}>.hex
    COMMAND ${CMAKE_OBJDUMP} -x -D $<TARGET_FILE:${TARGET_FILE}> > $<TARGET_FILE:${TARGET_FILE}>.s
    COMMAND ${CMAKE_SIZE} $<TARGET_FILE:${TARGET_FILE}>
    COMMENT "Converting ELF to binary and hex, and showing size"
)